package zju.lzy.iotclient;

import com.alibaba.fastjson.JSONObject;
import org.apache.juli.logging.LogFactory;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import zju.lzy.dto.IOTMessage;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;

public class TestIot {
    static String mqttServer = "tcp://127.0.0.1:1883";
    static String topic = "testapp";
    static String clientPrefix = "device";

    private static final Logger logger = LoggerFactory.getLogger(TestIot.class);

    public static void main(String[] args) throws MqttException, InterruptedException {
        MemoryPersistence mem = new MemoryPersistence();
        MqttClient client = new MqttClient(mqttServer, "myId2", mem);
        client.connect();
        client.subscribe(topic, 2);
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        client.setCallback(new MqttCallbackExtended() {
            @Override
            public void connectComplete(boolean reconnect, String serverURI) {
                System.out.println("");
            }

            @Override
            public void connectionLost(Throwable cause) {

            }

            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                System.out.println(new String(message.getPayload()));

            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {

            }
        });

        // 发的和收的客户端不能是同一个
        MqttClient sender = new MqttClient(mqttServer,"sender",new MemoryPersistence());
        sender.connect();
        while (true) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("hahaha");
            try {
                sender.publish(topic,new MqttMessage("asd".getBytes(StandardCharsets.UTF_8)));
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }

    }
}
